import React, { useState, useRef, useEffect } from 'react';
import { Image, Divider, Modal, Form, message, Button, Tree, Space, Tabs, Menu, Checkbox } from 'antd';
import { PlusOutlined, ExclamationCircleOutlined, EditOutlined, CreditCardOutlined, UpCircleOutlined } from '@ant-design/icons';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { queryDict, updateDict, addDict, queryDictTree,removeDict,batchRemoveDict } from '@/services/dict';
import { addDicType } from '@/services/dictype';

import styles from './index.less';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import CreateTypeForm from './components/CreateTypeForm';
const { confirm } = Modal;



/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addDict(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 添加节点
 * @param fields
 */
 const handleAddType = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addDicType(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDict(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
 const handleRemove = async (record: API.DictItem) => {
  const hide = message.loading('正在删除');
 
  try {
    await removeDict({dictCode:record.dictCode,typeId:record.typeId});
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const definition: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [createTypeModalVisible, handleTypeModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [treeData, setTreeData] = useState<API.TreeNodeItem[]>([]);
  const [typeId, setTypeId] = useState<number>();
  const [typeName, setTypeName] = useState<string>();

  const onSelect = (keys: React.Key[], info: any) => {
    setTypeId(info.node.key)
    setTypeName(info.node.title)
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  const onExpand = () => {
    console.log('Trigger Expand');
  };

  const columns: ProColumns[] = [
    {
      title: '编码',
      dataIndex: 'dictCode',
    },
    {
      title: '名称',
      dataIndex: 'dictValue',
    },
    {
      title: '图标',
      dataIndex: 'picCode',
      hideInSearch: true,
      renderText: (icon: string) => {
        if (icon) {
          return <Image src={'/img/' + icon} width={100} preview={false} />;
        }
        return icon;
      },
    },
    {
      title: '描述',
      dataIndex: 'dictDescription',
      hideInSearch: true,
      width: 200,
      ellipsis: true,
    },
    {
      title: '是否禁用',
      dataIndex: 'deleteFlag',
      hideInSearch: true,
      valueEnum: {
        0: { text: '启用', status: 'Success' },
        1: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={async () => {
              handleUpdateModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={() => {
            confirm({
              title: '您确定要删除吗?',
              icon: <ExclamationCircleOutlined />,
              async onOk() {
                await handleRemove(record);
                actionRef.current?.reload();
              },
              onCancel() {
                console.log('Cancel');
              },
            });
          }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  const queryTreeData = async() => {
    const trees = await queryDictTree();
    setTypeId(trees[0].value);
    setTypeName(trees[0].title);
    setTreeData(trees);
  }

  useEffect(() => {
    queryTreeData();
  }, []);

  const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>([]);
  const onSelectChange = async (sKeys ) => {
    setSelectedRowKeys(sKeys);

  };
  
//批量删除
const batchRemove = async () => {
  const hide = message.loading('正在删除');
  try {
    await batchRemoveDict({ ids: selectedRowKeys.join(','),typeId});
    setSelectedRowKeys([]);
    hide();
    message.success('删除成功，正在刷新！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};

  return (
  <div className={styles.main}>
    {treeData && treeData.length ?
      <>
      <div className={styles.leftMenu}>
        <Space direction="vertical" style={{ width: '90%' }}>
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleTypeModalVisible(true)}>
              新增
          </Button>
         <Tree
            //multiple
            defaultExpandAll={false}
            defaultExpandedKeys={['0-0']}
            onSelect={onSelect}
            onExpand={onExpand}
            defaultSelectedKeys={typeId+""}
            treeData={treeData}
          />
        </Space>
      </div>
      <div className={styles.right}>
       <ProTable
          headerTitle=""
          actionRef={actionRef}
          rowKey="dictCode"
          toolBarRender={(action, { selectedRows }) => [
            <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
              新增
            </Button>
          ]}
          rowSelection={{selectedRowKeys,onChange: onSelectChange}}
          tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                  取消选择
                </a>
              </span>
            </Space>
          )}
          tableAlertOptionRender={() => {
            return (
              <Space size={16}>
                <a  onClick={() => {
                confirm({
                  title: '您确定要批量删除吗?',
                  icon: <ExclamationCircleOutlined />,
                  async onOk() {
                    await batchRemove();
                    actionRef.current?.reload();
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }} >批量删除</a>
              
              </Space>
            );
          }}
          options={false}
          request={(params) => queryDict({ ...params, typeId: typeId })}
          columns={columns}
          pagination={{
            defaultCurrent: 1,
            defaultPageSize: 10,
          }}
        /> 
      <CreateForm
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => handleModalVisible(false)}
          modalVisible={createModalVisible}
          typeId={typeId}
          typeName={typeName}
        />

         <CreateTypeForm
          onSubmit={async (value) => {
            const success = await handleAddType(value);
            if (success) {
              handleTypeModalVisible(false);
              queryTreeData(1);
            }
          }}
          onCancel={() => handleTypeModalVisible(false)}
          modalVisible={createTypeModalVisible}
        
        />
        {formValues && Object.keys(formValues).length ? (
          <UpdateForm
            onSubmit={async (value) => {
              const success = await handleUpdate(value);
              if (success) {
                handleModalVisible(false);
                setFormValues({});
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            onCancel={() => {
              handleUpdateModalVisible(false);
              setFormValues({});
            }}
            updateModalVisible={updateModalVisible}
            values={formValues}
            treeData={treeData}
          />
        ) : null}
      </div></>:null}
    </div>
  );
};

export default definition;